﻿Imports System.IO.Compression
Imports System.Text
Imports System.IO

'http://www.csharphelp.com/2007/09/compress-and-decompress-strings-in-c/
Namespace OfflineLibrary_WPF
	Module Compression

		'custom
		Public Function CompressStringToByte(text As String) As Byte()
			Dim buffer As Byte() = Encoding.UTF8.GetBytes(text)
			Using ms As New MemoryStream
				Using zip As New GZipStream(ms, CompressionMode.Compress, True)
					zip.Write(buffer, 0, buffer.Length)
				End Using

				Return ms.ToArray
			End Using

		End Function

		'custom
		Public Function DecompressByteToString(compressedBytes As Byte()) As String
			Using msIn As New MemoryStream(compressedBytes)
				Using msOut As New MemoryStream
					Using zip As New GZipStream(msIn, CompressionMode.Decompress)
						zip.CopyTo(msOut)
					End Using

					Return Encoding.UTF8.GetChars(msOut.ToArray)
				End Using
			End Using
		End Function

		'original
		Public Function Compress(text As String) As String
			Dim buffer As Byte() = Encoding.UTF8.GetBytes(text)
			Dim ms As New MemoryStream
			Using zip As New GZipStream(ms, CompressionMode.Compress, True)
				zip.Write(buffer, 0, buffer.Length)
			End Using

			ms.Position = 0
			Dim outStream As New MemoryStream()

			Dim compressed(ms.Length) As Byte
			ms.Read(compressed, 0, compressed.Length)

			Dim gzBuffer(compressed.Length + 4) As Byte
			System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length)
			System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4)
			Return Convert.ToBase64String(gzBuffer)
		End Function

		'original
		Public Function Decompress(compressedText As String) As String
			Dim gzBuffer As Byte() = Convert.FromBase64String(compressedText)
			Using ms As New MemoryStream()
				Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
				ms.Write(gzBuffer, 4, gzBuffer.Length - 4)

				Dim buffer(msgLength) As Byte

				ms.Position = 0
				Using zip As New GZipStream(ms, CompressionMode.Decompress)
					zip.Read(buffer, 0, buffer.Length)
				End Using

				Return Encoding.UTF8.GetString(buffer)
			End Using
		End Function

	End Module
End Namespace